import type { BasicFormProps } from '@/components/form/src/props';
import type { FormActionType, FormSchema } from '@/components/form';
import { filterObjectParams } from '@/utils/common';

interface UseFormActionContext {
  emits: any;
  getProps: ComputedRef<BasicFormProps>;
  getSchema: ComputedRef<FormSchema[]>;
  formModel: Recordable;
  formElRef: Ref<FormActionType>;
  defaultFormModel: Ref<Recordable>;
  submitLoading: Ref<boolean>;
}

export function useFormEvents({
  emits,
  getProps,
  formModel,
  getSchema,
  formElRef,
  defaultFormModel,
  submitLoading,
}: UseFormActionContext) {
  /**
   * 验证
   */
  async function validate() {
    console.log('🚀 ----- getProps', getProps);
    return unref(formElRef)?.validate();
  }

  /**
   * 提交表单
   */
  async function handleSubmit(): Promise<object | boolean> {
    emits('submit', { ...getFieldsValue() });
    return false;
  }

  /**
   * 清空校验
   */
  async function clearValidate() {
    // @ts-ignore
    await unref(formElRef)?.restoreValidation();
  }

  /**
   * 重置
   */
  async function resetFields(): Promise<void> {
    console.log('🚀 ----- defaultFormModel', defaultFormModel);
  }

  /**
   * 获取表单值
   */
  function getFieldsValue(): Recordable {
    const formEl = unref(formElRef);
    if (!formEl) {
      return {};
    }
    return filterObjectParams(toRaw(unref(formModel)));
  }

  /**
   * 设置表单字段值
   * @param values
   */
  async function setFieldsValue(values: Recordable): Promise<void> {
    const fields = unref(getSchema)
      .map(item => item.field)
      .filter(Boolean);

    Object.keys(values).forEach(key => {
      const value = values[key];
      if (fields.includes(key)) {
        formModel[key] = value;
      }
    });
  }

  /**
   * 设置表单值
   * @param value
   */
  function setLoading(value: boolean): void {
    submitLoading.value = value;
  }

  return {
    handleSubmit,
    validate,
    clearValidate,
    resetFields,
    getFieldsValue,
    setFieldsValue,
    setLoading,
  };
}
